/*
 * Filename:    PerformanceIndicatorsController.java
 * Copyright:   2014 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2014-11-10
 */
package com.paic.mhis.hcpms.assessment.web;

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jfree.util.Log;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Table;
import com.lowagie.text.rtf.RtfWriter2;
import com.paic.mhis.hcpms.agreement.healthcareprovider.util.HttpProcessUtil;
import com.paic.mhis.hcpms.assessment.biz.service.PerformanceIndicatorsService;
import com.paic.mhis.hcpms.assessment.util.AssessmentUtils;
import com.paic.pafa.appclient.annotation.BizServicesProxy;
import com.paic.pafa.exceptions.BusinessException;

/**
 * Description:
 * 
 * @author: EX-LUANDEBIAO001
 * @version:
 */
@Controller
@RequestMapping("/assessment/")
public class PerformanceRankingController {
	private static final Logger LOG = Logger
			.getLogger(PerformanceRankingController.class);

	@BizServicesProxy(beanName = "performanceIndicatorsService")
	private PerformanceIndicatorsService performanceIndicatorsService;

	@Value("${rtfReportTemplatePath}")
	private String rtfReportTemplatePath;

	/**
	 * 
	 * Description: 查询各指标权重
	 * 
	 * @param request
	 * @return
	 * 
	 *         Modification History: Date Version Author Description
	 *         ------------
	 *         ------------------------------------------------------ 2015-3-25
	 *         mhis_hcpms EX-HUANGJUN003 创建
	 */
	@RequestMapping("getFullMark.do")
	@ResponseBody
	public List<Map<String, Object>> findFullMark(HttpServletRequest request) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		list = performanceIndicatorsService.findFullMark();
		return list;
	}

	/**
	 * 
	 * Description: 查询医院综合评价排名
	 * 
	 * @param request
	 * @return
	 * 
	 *         Modification History: Date Version Author Description
	 *         ------------
	 *         ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	@RequestMapping("getRankingInfos.do")
	@ResponseBody
	public Map<String, Object> findIndicators(HttpServletRequest request) {
		Map<String, Object> result = null;
		try {
			int page = Integer.parseInt(request.getParameter("page"));
			int pageSize = Integer.parseInt(request.getParameter("limit"));

			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("grade", request.getParameter("grade"));
			paramMap.put("kpiTime", request.getParameter("kpiTime"));
			paramMap.put("lastKpiTime", AssessmentUtils.getLastMonth(
					request.getParameter("kpiTime"), "yyyy-MM"));
			paramMap.put("backHospitalName",
					request.getParameter("backHospitalName"));
			result = performanceIndicatorsService.getRankingInfos(page,
					pageSize, paramMap);

		} catch (Exception e) {
			result = HttpProcessUtil.processException(e);
		}

		return result;
	}

	/**
	 * 
	 * Description:查询医院综合评价排名
	 * 
	 * @param request
	 * @param response
	 * 
	 *            Modification History: Date Version Author Description
	 *            ----------
	 *            --------------------------------------------------------
	 *            2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	@RequestMapping("hospitalRankingCreateWord.do")
	@ResponseBody
	public Map<String, Object> createHospitalRankingTable(
			HttpServletRequest request, HttpServletResponse response) {
		String filePath = rtfReportTemplatePath + "assessment/ranking/";

		// String filePath = request.getSession().getServletContext()
		// .getRealPath("/")
		// + "RTFReportTemplateDir/assessment/ranking/";
		Map<String, Object> mapResult = new HashMap<String, Object>();
		boolean flag = true;
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("grade", request.getParameter("grade"));
			paramMap.put("kpiTime", request.getParameter("kpiTime"));
			paramMap.put("lastKpiTime", AssessmentUtils.getLastMonth(
					request.getParameter("kpiTime"), "yyyy-MM"));
			paramMap.put("backHospitalName",
					request.getParameter("backHospitalName"));
			paramMap.put("backHospitalNameReal",
					request.getParameter("backHospitalNameReal"));
			List<Map<String, Object>> result = performanceIndicatorsService
					.hospitalRankingTable(paramMap);
			createTable(result, paramMap, filePath);
		} catch (Exception e) {
			LOG.error(e, e);
			flag = false;
			mapResult.put("msg", "导出word失败");
		} finally {
			mapResult.put("flag", flag);
		}
		return mapResult;

	}

	/**
	 * 
	 * Description: 导出rtf文件
	 * 
	 * @param request
	 * @param response
	 * 
	 *            Modification History: Date Version Author Description
	 *            ----------
	 *            --------------------------------------------------------
	 *            2015-3-19 mhis_hcpms EX-LUANDEBIAO001 创建
	 */
	@RequestMapping("hospitalRankingExportWord.do")
	@ResponseBody
	public void exportWordHospitalRankingTable(HttpServletRequest request,
			HttpServletResponse response) {
		String grade = request.getParameter("grade") + "";
		String kpiTime = request.getParameter("kpiTime") + "";
		String backHospitalNameReal = request
				.getParameter("backHospitalNameReal") + "";
		// String filePath = request.getRealPath("/")
		// + "RTFReportDir/assessment/ranking/";
		String filePath = rtfReportTemplatePath + "assessment/ranking/";
		String titleString = "";

		if (StringUtils.equals(backHospitalNameReal, "")) {
			if (StringUtils.equals(backHospitalNameReal, "")
					&& StringUtils.equals(grade, "")) {
				titleString = "厦门医保" + kpiTime;
			} else {
				titleString = "厦门" + getHospitalLevel(grade) + "医保综合评价排名"
						+ kpiTime;
			}

		} else {
			titleString = backHospitalNameReal + "综合评价排名" + kpiTime;
		}

		// String filePath = request.getSession().getServletContext()
		// .getRealPath("/")
		// + "RTFReportTemplateDir/assessment/ranking/";
		try {
			FileInputStream fis = new FileInputStream(new File(filePath
					+ titleString + ".rtf"));

			initResponse(response, titleString);
			byte[] bytes = new byte[1024];
			while (fis.read(bytes) != -1) {
				response.getOutputStream().write(bytes);
			}
			response.getOutputStream().flush();
			response.getOutputStream().close();
			fis.close();
		} catch (Exception e) {
			HttpProcessUtil.processException(e);
			LOG.error(e, e);
		}

	}

	/**
	 * 
	 * Description: 初始化
	 * 
	 * @param response
	 * @param name
	 *            文件名
	 * 
	 *            Modification History: Date Version Author Description
	 *            ----------
	 *            --------------------------------------------------------
	 *            2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	private void initResponse(HttpServletResponse response, String name) {
		try {
			response.addHeader("Pragma", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
			response.reset();
			response.setContentType("APPLICATION/OCTET-STREAM");
			String fileName = new String((name).getBytes("utf-8"), "ISO8859-1")
					+ ".rtf";
			response.setHeader("content-disposition", "attachment;fileName=\""
					+ fileName + "\"");
		} catch (UnsupportedEncodingException e) {
			LOG.error("导出Excel时发生异常,异常原因:" + e.getMessage());
		}
	}

	/**
	 * 
	 * Description:生成医院综合评价排名表格文档
	 * 
	 * @param result
	 *            综合评价排名查询的结果
	 * @param level
	 *            医院的等级
	 * @param filePath
	 *            文件保存的路径
	 * @throws Exception
	 * 
	 *             Modification History: Date Version Author Description
	 *             --------
	 *             ----------------------------------------------------------
	 *             2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	private void createTable(List<Map<String, Object>> result,
			Map<String, Object> map, String filePath) throws BusinessException {
		try {
			String level = map.get("grade") + "";
			String backHospitalNameReal = map.get("backHospitalNameReal") + "";
			String kpiTime = map.get("kpiTime") + "";
			// 获得文档对象
			Document doc = new Document();
			// table对象
			Table table = null;
			String titleString = "";

			if (StringUtils.equals(backHospitalNameReal, "")) {
				if (StringUtils.equals(backHospitalNameReal, "")
						&& StringUtils.equals(level, "")) {
					titleString = "厦门医保" + kpiTime;
				} else {
					titleString = "厦门" + getHospitalLevel(level) + "医保综合评价排名"
							+ kpiTime;
				}
			} else {
				titleString = backHospitalNameReal + "综合评价排名" + kpiTime;
			}

			RtfWriter2.getInstance(doc, new FileOutputStream(filePath
					+ titleString + ".rtf"));
			doc.open();
			table = new Table(11, result.size() + 1);
			table.setPadding(10);
			table.setWidth(145F);
			table.setBackgroundColor(Color.BLACK);
			int[] ins = { 70, 250, 90, 110, 110, 110, 110, 150, 150, 120, 200 };
			table.setWidths(ins);

			Font font = new Font();
			font.setStyle(Font.BOLD);
			font.setSize(14);
			Paragraph title = new Paragraph(titleString, font);
			title.setAlignment(Element.ALIGN_CENTER);
			doc.add(title);
			// 添加表头元素
			addHeaderCell(table);
			addBodyCell(table, result);
			doc.add(table);
			doc.setPageSize(new Rectangle(850F, 600F));
			doc.close();
		} catch (Exception e) {
			HttpProcessUtil.processException(e);
			LOG.error(e, e);
		}
	}

	/**
	 * 
	 * Description: 添加表头元素
	 * 
	 * @param table
	 *            需要生成的表格对象
	 * 
	 *            Modification History: Date Version Author Description
	 *            ----------
	 *            --------------------------------------------------------
	 *            2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 * @throws BadElementException
	 */
	public void addHeaderCell(Table table) throws BadElementException {
		// 添加表头元素
		String[] title = { "排名", "机构", "总分数 ", "住院费用得分 ", "门诊费用得分", "FWA审核得分 ",
				"个人负担得分", "医保政策依从性得分 ", "医保审核管理得分 ", "信息化得分", "较上月排名上升/下降" };
		for (int i = 0; i < title.length; i++) {
			Font fontBody = new Font();
			fontBody.setSize(11);
			Paragraph body = new Paragraph(title[i], fontBody);
			Cell cell = new Cell(body);
			cell.setHeader(true);
			cell.setBackgroundColor(new Color(149, 221, 158));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
		}
		table.endHeaders();
	}

	/**
	 * 
	 * Description:添加内容元素
	 * 
	 * @param table
	 *            需要生成的表格对象
	 * @param list
	 *            查询所得的结果集
	 * 
	 *            Modification History: Date Version Author Description
	 *            ----------
	 *            --------------------------------------------------------
	 *            2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 * @throws BadElementException
	 */
	public void addBodyCell(Table table, List<Map<String, Object>> list)
			throws BadElementException {
		Font fontBody = new Font();
		fontBody.setSize(11);
		String[] title = { "RK", "HOSPITAL", "IND01", "IND010101", "IND010102",
				"IND010103", "IND010201", "IND010301", "IND010302", "IND010401" };
		for (Map<String, Object> map : list) {
			for (int j = 0; j < title.length; j++) {
				Paragraph body = new Paragraph(getRealValue(map.get(title[j])),
						fontBody);
				Cell cell = new Cell(body);
				cell.setBorderWidth(1);
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setVerticalAlignment(Element.ALIGN_CENTER);
				table.addCell(cell);
			}
			String range = (String) map.get("RKCHANGE");
			if (StringUtils.equals(range, "0")) {
				range = "不变";
			} else if (StringUtils.equals(range, "1")) {
				range = "上升";
			} else if (StringUtils.equals(range, "-1")) {
				range = "下降";
			}
			Paragraph bodyy = new Paragraph(range, fontBody);
			Cell cell = new Cell(bodyy);
			cell.setBorderWidth(1);
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
		}
	}

	/**
	 * 
	 * Description:如果对象为null 则返回"" 否则toString
	 * 
	 * @param obj
	 *            传入的排名的属性值
	 * @return 处理obj后返回的String对象
	 * 
	 *         Modification History: Date Version Author Description
	 *         ------------
	 *         ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	public String getRealValue(Object obj) {
		if (obj == null) {
			return "";
		} else {
			return obj.toString();
		}
	}

	/**
	 * 
	 * Description:获得医院的等级
	 * 
	 * @param str
	 *            医院的等级
	 * @return 转换后的医院的等级
	 * 
	 *         Modification History: Date Version Author Description
	 *         ------------
	 *         ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	public String getHospitalLevel(String str) {
		String newStr = "";

		if (str == null) {
			newStr = "全市医疗机构";
		}
		if ("4".equals(str)) {
			newStr = "一级及以下医院";
		}
		if ("3".equals(str)) {
			newStr = "二级医院";
		}
		if ("2".equals(str)) {
			newStr = "三级医院";
		}
		return newStr;
	}

}
